import { ApiResp, OrderConfirmViewResp } from "@/types/response"
import { apiClient } from "."
import { Order } from "@/types/order"


export const orderService = {
  confirmOrderView: async (items: number[]) => {
    try {
      const response = await apiClient.post<OrderConfirmViewResp>("/order/confirm-view", { items })
      if (response.data.code === 0 && "data" in response.data) {
        return response.data.data
      }      
      else if (response.data.code !== 0 && "message" in response.data) {
        console.error("Error:", response.data.message)
        return null
      }
      return null
    } catch (error) {
      console.error("Error:", error)
      return null
    }
  },


  submitOrder: async (payload:  {skuIds: number[], addressId: number, note?: string}) => {
    try {
      const response = await apiClient.post<ApiResp<number>>("/order/submit", payload)
      if (response.data.code === 0 && "data" in response.data) {
        return response.data.data
      } else if (response.data.code !== 0 && "message" in response.data){
        console.error("Error:", response.data.message)
        return null
      }
      return null
    } catch (error) {
      console.error("Error:", error)
      return null
    }

  },


  orderList: async () => {

    try {
      const response = await apiClient.get<ApiResp<Order[]>>("/order/list")
      if (response.data.code === 0 && "data" in response.data) {
        return response.data.data
      } else if (response.data.code !== 0 && "message" in response.data){
        console.error("Error:", response.data.message)
        return null
      }
      return null
    } catch (error) {
      console.error("Error:", error)
      return null
    }

  },

  cancelOrder: async (orderId: number) => {
    try {
      const response = await apiClient.post<ApiResp<string>>("/order/cancel", { orderId })
      if (response.data.code === 0 && "data" in response.data) {
        return response.data.data
      } else if (response.data.code !== 0 && "message" in response.data){
        console.error("Error:", response.data.message)
        return null
      }
      return null
    } catch (error) {
      console.error("Error:", error)
      return null
    }
  },


  receivedOrder: async (orderId: number) => {
    try {
      const response = await apiClient.post<ApiResp<string>>("/order/receive", { orderId })
      if (response.data.code === 0 && "data" in response.data) {
        return response.data.data
      } else if (response.data.code !== 0 && "message" in response.data){
        console.error("Error:", response.data.message)
        return null
      }
      return null
    } catch (error) {
      console.error("Error:", error)
      return null
    }
  }

}